//
//  ReplenishmentVc.swift
//  Pods
//
//  Created by eme on 2017/4/20.
//
//

import UIKit
import UtilCore
import RickonCore
import Kingfisher
import EmptyDataView
import RxSwift
import AddCarCore
import BrandonCore

class ReplenishmentVc: Empty_TVc,AddCarProtocol {
    
    /****************************Storyboard UI设置区域****************************/
    @IBOutlet weak var product_Tv: UITableView!
    
    @IBOutlet weak var filter_Brand_Btn: UIButton!
    
    @IBOutlet weak var pdname_Tf: UITextField!
    
    
    @IBOutlet weak var pdname_V: UIView!
    
    
    @IBOutlet weak var seperateLine_V: UIView!
    var keyWord:String?
    /*----------------------------   自定义属性区域    ----------------------------*/
    var manageVm:ReplenishmentVm?
    var selectedModel:BrlistModel?
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    var productList:[HpProductModel]? {
        didSet {
            if let _ = self.productList {
                self.product_Tv.reloadData()
                
            }
        }
    }
    
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        if let model = self.selectedModel {
            self.manageVm?.brid_Param.value = model.brid
            self.filter_Brand_Btn.setTitle(model.brname, for: .normal)
        }else{
            if self.manageVm?.brid_Param.value != "" {
                self.manageVm?.brid_Param.value = ""
            }
            self.filter_Brand_Btn.setTitle("品牌", for: .normal)
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // sender 一般是 button，但可以是任何东西
        if let identifier = segue.identifier { // 检查是否 nil
            switch identifier {
            case "FilterBrand_Vc":
                if let vc = segue.destination as? FilterBrand_Vc {
                    vc.brlist = sender as? [BrlistModel]
                    vc.hasSelected_BrModel = self.selectedModel
                    vc.didSelectBrandModel_Closure = { [unowned self] brandModel in
                        self.selectedModel = brandModel
                    }
                }
            default: break
            }
        }
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        header.setRefreshingTarget(self, refreshingAction: #selector(ReplenishmentVc.headerRefresh))
        self.product_Tv.mj_header = header
        // 上拉刷新
        footer.setRefreshingTarget(self, refreshingAction: #selector(ReplenishmentVc.footerRefresh))
        footer.isAutomaticallyHidden = true
        self.product_Tv.mj_footer = footer
        self.product_Tv.dzn_tv_emptyDelegate = self
        self.product_Tv.dzn_tv_emptyDataSource = self
        self.product_Tv.tableFooterView = UIView()
        
        self.pdname_V.changeBorderColor(UIColor(hex:"eaebed"), cornerRadius: 6.0)
        
        self.seperateLine_V.backgroundColor = Theme.v.separate_Line
    }
    
    
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        /**
         *  初始化viewmodel
         */
        self.manageVm = ReplenishmentVm(
            input: (
                refreshTriger:  Observable.of(rx.sentMessage(#selector(ReplenishmentVc.headerRefresh)).map { _ in () }, Observable.just())
                    .merge().filter{ _ -> Bool in
                        if case  .audited = AppData.appState{
                            return true
                        }else{
                            AuditInfoView.showByView(supView: self.view)
                            return false
                        }
                },
                loadMoreTriger: rx.sentMessage(#selector(ReplenishmentVc.footerRefresh)).map { _ in () }
        ))
        /**
         *  通过vm 的hasNextPage 配置数据是否加载完毕
         */
        self.manageVm?.hasNextPage.asDriver().asObservable().subscribe(onNext:{[unowned self] hasNextPage in
            if !hasNextPage {
                self.footer.endRefreshingWithNoMoreData()
            }else {
                /** 重置没有更多的数据（消除没有更多数据的状态） */
                self.footer.resetNoMoreData()
            }
        }).addDisposableTo(disposeBag)
        self.manageVm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        //        self.manageVm?.refreshing.asObservable().bindTo(self.view.rx_loading).addDisposableTo(disposeBag)
        self.manageVm?.productsElements.asObservable().subscribe(onNext:{[unowned self] list in
            self.showEmptyView = true
            self.productList = list
        }).addDisposableTo(disposeBag)
        self.filter_Brand_Btn.rx.tap.subscribe(onNext:{ _ in
            self.manageVm?.productrapidbrandlist_Subject.onNext("")
        }).addDisposableTo(disposeBag)
        self.manageVm?.productrapidbrandlist_Success.subscribe(onNext:{ list in
            self.performSegue(withIdentifier: "FilterBrand_Vc", sender: list)
        }).addDisposableTo(disposeBag)
        self.manageVm?.glproductskus_Success.subscribe(onNext:{ productItem in
            self.addCar(vc: self, model: productItem,footerButonType:"jrphd"){ product , param,_ in
                self.manageVm?.addcartsSubject.onNext(param["osCarts"] as! NSString)
            }
        }).addDisposableTo(disposeBag)
        self.manageVm?.addcartsSuccess.subscribe(onNext:{ rel in
            print(rel)
            self.view.toastErrorCode(100041002)
        }).addDisposableTo(disposeBag)
    }
    
    // 顶部刷新
    func headerRefresh(){
        // 结束刷新
        self.product_Tv.mj_header.endRefreshing()
    }
    
    func footerRefresh(){
        self.product_Tv.mj_footer.endRefreshing()
    }
}
extension ReplenishmentVc:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let productList = self.productList{
            return productList.count
        }
        return 0
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ReplenishmentTCell") as! ReplenishmentTCell
        let item = self.productList![indexPath.row]
        cell.item = item
        cell.addCart_Closure = {[unowned self] _ in
            self.manageVm?.glproductskus_Subject.onNext("\(item.pdid)")
        }
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 153
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let model = self.productList![indexPath.row]
        _ = "productdetail".openURL(["pdid":"\(model.pdid)"])
    }
}
extension ReplenishmentVc:EmptyDataSource{
    
    func description(emptyView scrollView: UIScrollView) -> NSAttributedString? {
        
        if let keyWord = self.keyWord{
            let starstr = "\(keyWord)"
            let str = "抱歉，没有找到与\(starstr)相关的商品。您可以换个词再试试"
            let attributeString = NSMutableAttributedString(string: str)
            attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor(hex: "e31436"), range: NSMakeRange(str.indexOf(starstr)!, starstr.characters.count))
            return attributeString
        }else{
            return Theme.getEmptyDesc("您还未购买过商品")
        }
        
    }
    func image(emptyView scrollView: UIScrollView) -> UIImage? {
        
        if self.keyWord != nil{
            return UIImage.init(named: "searchproduct-empty", in: RobbCore.bundle, compatibleWith: nil)
        }else{
            return UIImage.init(named: "shopcart_empty", in: RobbCore.bundle, compatibleWith: nil)
        }
    }
    
    func backgroundColor(emptyView scrollView: UIScrollView) -> UIColor?{
        return UIColor.white
    }
}
extension ReplenishmentVc:UISearchBarDelegate{
    
}
extension ReplenishmentVc:UITextFieldDelegate{
    func textFieldDidEndEditing(_ textField: UITextField) {
        requestToFilter(textField: textField)
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        //        requestToFilter(textField: textField)
        textField.resignFirstResponder()
        return true
    }
    func requestToFilter(textField: UITextField)  {
        
        if let text = textField.text {
            if text.characters.count > 100{
                self.view.toastErrorCode(100011002)
            }else{
                self.keyWord = text
                self.manageVm?.pdname_Param.value = text
            }
        }
    }
}
